//
//  XQOrderDetailEmergencyController.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/11.
//

import UIKit
import Contacts
import ContactsUI
import HandyJSON

class XQOrderDetailEmergencyController: XQBaseController {
    
    var districtListModel : [XQEmergencyDistrictModel]?
    
    var jsonList : [[String : String]] = []
    
    var phoneSection : Int = -1

    private lazy var bgImageView : UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "detail_publish_bg")
        imageView.isUserInteractionEnabled = true
        return imageView
    }()
    
    private lazy var contentView : UIView = {
        let view = UIView()
        view.frame = CGRect(x: 15, y:UIDevice.xq_statusHeight() + 73, width: UIDevice.xq_width() - 30, height: UIDevice.xq_height() - UIDevice.xq_statusHeight() - 73)
        view.setRoundCorners([.topLeft,.topRight], radius: 16)
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var tableView : UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.backgroundColor = .clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.isScrollEnabled = true
        tableView.register(XQEmergencyCell.self, forCellReuseIdentifier: "XQEmergencyCell")
        tableView.showsVerticalScrollIndicator = false
        return tableView
    }()
    
    private lazy var netBtn : UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Next", for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .medium)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = .mainTextColor
        btn.layer.cornerRadius = 30
        btn.addTarget(self, action: #selector(nextClick), for: .touchUpInside)
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()   
        makeUI()
        makeConstraints()
            
        startTime = XQTimeTool.nowTime()
        
        refreshData()
        
        XQHud.showLoading(controller: self)
    }
    
    private func makeUI() {
        self.view.insertSubview(self.bgImageView, belowSubview: self.navigationBar)
        self.bgImageView.addSubview(self.contentView)
        self.contentView.addSubview(self.tableView)
        self.contentView.addSubview(self.netBtn)
    }
    
    private func makeConstraints() {
        self.bgImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.contentView.snp.makeConstraints { make in
            make.top.equalTo(UIDevice.xq_statusHeight() + 73)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.bottom.equalTo(0)
        }
        self.netBtn.snp.makeConstraints { make in
            make.left.equalTo(32)
            make.right.equalTo(-32)
            make.height.equalTo(54)
            make.bottom.equalTo(-UIDevice.xq_safeTop() - 24)
        }
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(self.netBtn.snp.top).offset(-12)
        }
    }
        
    private func refreshData() {
        let params : [String : String] = [
            "taxes" : orderId
        ]
        
        XQNetworkManager.shared.postRequest(url: "/figures/inequities", parameters: params) {[weak self] response, error in
            guard let srongify = self else {return}
            XQHud.hideLoading(controller: srongify)
            if (response?.object == 0) {
                if let model = XQEmergencyModel.deserialize(from: response?.procedure) {
                    srongify.districtListModel = model.district
                    srongify.updateJsonData()
                }
            }
        }
    }
    
    @objc private func nextClick() {
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: jsonList, options: [])
            
            if let jsonString = String(data: jsonData, encoding: .utf8) {

                let params : [String : String] = [
                    "taxes" : orderId,
                    "procedure" : jsonString
                ]
                
                XQHud.showLoading(controller: self)
                XQNetworkManager.shared.postRequest(url: "/figures/adverse", parameters: params) {[weak self] response, error in
                    guard let srongify = self else {return}
                    XQHud.hideLoading(controller: srongify)
                    if (response?.object == 0) {
                        srongify.navigationController?.popViewController(animated: true)
                        srongify.notifyRisk()
                    }else {
                        XQHud.showToast(message: response?.patients ?? "Network Connection Error")
                    }
                }
            }
        } catch {
            print("Error converting array to JSON string: \(error)")
        }
    }
    
    private func notifyRisk() {
        endTime = XQTimeTool.nowTime()
        
        XQAnalysisManager.shared.notifyRisk(numberType: "7", longitude: self.longitude, latitude: self.latitude, startT: self.startTime, endT: self.endTime, orderId: "")
    }
}

extension XQOrderDetailEmergencyController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.jsonList.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "XQEmergencyCell", for: indexPath) as! XQEmergencyCell
        
        if let list = districtListModel {
            if (indexPath.section < list.count) {
                let m = list[indexPath.section]
                cell.phoneView.title = m.appointed
                cell.phoneView.placeHolder = m.republican
                cell.phoneView.content = getCellPhoneContent(indexPath: indexPath)
                cell.contactView.title = m.offenders
                cell.contactView.placeHolder = m.give
                cell.contactView.content = getCellReleationContent(indexPath: indexPath)
            }
        }
        cell.phoneView.onTapHandle = {[weak self] (text) in
            guard let srongify = self else {return}
            srongify.showContactPop(indexPath: indexPath)
        }
        cell.contactView.onTapHandle = {[weak self] (text) in
            guard let srongify = self else {return}
            srongify.showPopView(text: text, indexPath: indexPath)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 176
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = XQEmergencyHeaderView()
        
        if let list = districtListModel {
            if (section < list.count) {
                let m = list[section]
                headerView.content = m.accessing
            }
        }
        return headerView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 52
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView()
        return footerView
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}

extension XQOrderDetailEmergencyController {
    
    private func updateJsonData() {
        guard let list = districtListModel else {return}
        
        jsonList.removeAll()
        var dic : [String : String] = [:]
        for m in list {
            if m.democratic?.count != 0 {
                dic["democratic"] = m.democratic
            }
            if m.pardons?.count != 0 {
                dic["pardons"] = m.pardons
            }
            if m.observably?.count != 0 {
                dic["observably"] = m.observably
            }
            jsonList.append(dic)
        }
        
        self.tableView.reloadData()
    }
    
    private func getCellPhoneContent(indexPath : IndexPath) -> String {
        
        if (indexPath.section >= jsonList.count) {return ""}
        
        let json = jsonList[indexPath.section]
        
        let name = json["pardons"] ?? ""
        let phoneNumber = json["observably"] ?? ""
        
        if (name.count != 0 && phoneNumber.count != 0) {
            return "\(name) \(phoneNumber)"
        }else if (name.count != 0) {
            return name
        }else if (phoneNumber.count != 0) {
            return phoneNumber
        }else {
            return ""
        }
    }
    
    private func getCellReleationContent(indexPath : IndexPath) -> String {
        
        guard let list = districtListModel else {return ""}
        
        if (indexPath.section >= list.count) {return ""}
        
        let m = list[indexPath.section]
        
        let dic = jsonList[indexPath.section]
        
        let releationKey : String = dic["democratic"] ?? ""
        
        if (releationKey.isEmpty) {
            return ""
        }else {
            guard let thirdModel = m.third else {return ""}
            if (thirdModel.isEmpty) {return ""}
            
            var title = ""
            
            for m in thirdModel {
                if m.spectrophotometer == releationKey {
                    title = m.pardons ?? ""
                    break
                }
            }
            return title
        }
    }
    
    private func showPopView(text : String,indexPath : IndexPath) {
        
        guard let list = districtListModel else {return}
        
        let model = list[indexPath.section]
        
        guard let thirdList = model.third else {return}
                
        var titleList : [String] = []
        
        for m in thirdList {
            if (m.pardons?.count != 0) {
                titleList.append(m.pardons!)
            }
        }
        
        let contentView = XQBaseIdentityChoosePopView()
        contentView.frame = CGRect(x: 0, y:( UIDevice.xq_height() - 561) / 2, width: UIDevice.xq_width(), height: 561)
        contentView.sureHandle = {[weak self] (text) in
            guard let srongify = self else {return}
            XQHud.hidePop(controller: srongify)
            srongify.updateReleationJsonData(text: text, indexPath: indexPath)
        }
        contentView.cancelHandle = {
            XQHud.hidePop(controller: self)
        }

        XQHud.showPop(contentView,controller: self)
        contentView.dataSource = titleList
        contentView.selectData = getCellReleationContent(indexPath: indexPath)
    }
    
    private func updateReleationJsonData(text : String,indexPath : IndexPath) {
        
        guard let list = districtListModel else {return}
        
        let model = list[indexPath.section]
        
        var dic = jsonList[indexPath.section]
        
        var releationKey = ""
        
        for m in (model.third ?? []) {
            if m.pardons == text {
                releationKey = m.spectrophotometer ?? ""
                break
            }
        }
        
        dic["democratic"] = releationKey
        
        jsonList[indexPath.section] = dic
        
        self.tableView.reloadData()
    }
}

extension XQOrderDetailEmergencyController : CNContactPickerDelegate {
    
    private func showContactPop(indexPath : IndexPath) {
        self.phoneSection = indexPath.section
        
        let store = CNContactStore()
        store.requestAccess(for: .contacts) { granted, error in
            if granted {
                self.showContanceGranted()
            } else {
                self.showDinedView()
            }
        }
    }
    
    private func showContanceGranted() {
        DispatchQueue.main.async {
            let picker = CNContactPickerViewController()
            picker.delegate = self
            self.present(picker, animated: true)
        }
    }
    
    private func showDinedView() {
        DispatchQueue.main.async {
            XQAlertManager.showDeniedAccessPopAlert(on: self, message: "Please enable access to Contacts in Settings.")
        }
    }
    
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        let givenName = contact.givenName
        let familyName = contact.familyName
        let phoneValue = "\(givenName) \(familyName)"
        
        var pNumber = ""
        if contact.phoneNumbers.count > 0 {
            let p = contact.phoneNumbers.first?.value
            pNumber = p?.stringValue ?? ""
        }
        
        var dic = jsonList[phoneSection]
        dic["pardons"] = phoneValue
        dic["observably"] = pNumber
        
        jsonList[phoneSection] = dic
        
        self.tableView.reloadData()
        
        self.dismiss(animated: true)
        
        XQAnalysisManager.shared.notifyContacts()
    }
    
    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        self.dismiss(animated: true)
    }
}
